#include "HttpRequest.h"

HttpRequest::HttpRequest()
    : _version("HTTP/1.1")
{
}

// 1. 重置当前请求
void HttpRequest::ReSet()
{
    _method.clear();
    _path.clear();
    _version = "HTTP/1.1";
    _body.clear();
    std::smatch match;
    _matches.swap(match);
    _headers.clear();
    _params.clear();
}

// 2. 插入头部字段
void HttpRequest::SetHeader(const std::string &key, const std::string &val)
{
    _headers.insert({key, val});
}

// 3. 判断是否存在指定头部字段
bool HttpRequest::HasHeader(const std::string &key)
{
    auto it = _headers.find(key);
    if (it == _headers.end())
        return false;
    return true;
}

// 4. 获取指定头部字段
std::string HttpRequest::GetHeader(const std::string &key) const
{
    auto it = _headers.find(key);
    if (it == _headers.end())
        return "";
    return it->second;
}

// 5. 插入查询字符串
void HttpRequest::SetParam(std::string &key, std::string &val)
{
    _params.insert({key, val});
}

// 6. 判断是否有某个指定的查询字符串
bool HttpRequest::HasParam(std::string &key)
{
    auto it = _params.find(key);
    if (it == _params.end())
        return false;
    return true;
}

// 7. 获取指定的查询字符串
std::string HttpRequest::GetParam(std::string &key)
{
    auto it = _params.find(key);
    if (it == _params.end())
        return "";
    return it->second;
}

// 8. 获取正文长度
size_t HttpRequest::ContentLength()
{
    bool ret = HasHeader("Content-Length");
    if (ret == false)
        return 0;
    return std::stoi(GetHeader("Content-Length"));
}

// 9. 判断当前请求是否是短连接
bool HttpRequest::Close() const
{
    if (GetHeader("Connection") == "keep-alive")
        return false;
    return true;
}